<?php

// Last Modified: $Id: event_fns.php 237 2005-10-02 14:57:50Z plummer $

require_once('db_fns.php');

function get_user_eventids($attendee_id)
{
// Returns a pg formatted array of events owned by a given attendee_id
	if (!($conn = db_connect()))
		return false;
	$attendee_owned_events = pg_query( "SELECT event_id FROM event WHERE attendee_id = '$attendee_id'");
	if (!$attendee_owned_events)
		return false; 
	return $attendee_owned_events;
}

function get_event_details($event_id)
{
// gets the a postgres result resource for a given event_id, we also retrieve the attendee id that owns it and the name of that person (from the attendee db) for convenience. We can later pass this to record proc to get a handy assoc. array.
if (!($conn = db_connect()))
return false;
$result = pg_query("SELECT attendee.first_name, attendee.last_name, organization, event.* FROM event, attendee WHERE event.event_id = '$event_id' AND event.attendee_id = attendee.attendee_id");

if (!$result)
return false; 

return $result ;
}

function get_event_start_times($event_id)
{
//this function will return a numbered array containing only the times an event is supposed to run.
if (!($conn = db_connect()))
return false;

$result = pg_query("SELECT start_time FROM event_time WHERE event_id = '$event_id' ORDER BY start_time");

if (!$result)
return false; 

$numrows = pg_num_rows($result); 
for ($i=0; $i < $numrows; $i++) {
$start_time[$i] = pg_fetch_result($result,$i,"start_time");
}

return $start_time;
}

function add_event($event_values)
{
	// Add new event to the database

	$username = $_SESSION['username'];
	$attendee_id=$_SESSION['current_attendee_id'];
	extract ($event_values);

	if (!($conn = db_connect()))
		return false;

	// insert the new event
	$query = "INSERT INTO event (attendee_id, event_title,
	event_type, game_system, min_players, max_players, difficulty, familiarity,
	maturity, cost, equipment, description, notes, created, display_org, duration)
	VALUES ('$attendee_id', '$event_title', '$event_type', '$game_system',
	'$min_players', '$max_players', '$difficulty', '$familiarity', '$maturity', '$cost', '$equipment', '$description', '$notes',
	'$timestamp', '$display_org', '$duration hours')";
	if (!($result = pg_query($query))) 
		{
		echo $query;
		echo "Failed to submit event.<br>";
		return false;
		}

	$event_id = sql_last_inserted_id($result, event, event_id);
	foreach($multi_start_time as $start_time) {
		if (!pg_query("INSERT INTO event_time (event_id, start_time) VALUES ('$event_id', '$start_time')")) {
			echo "Failed updating timeslot at $start_time.<br>";
			return false;
			}
		if (!pg_query("INSERT INTO gm (gm_id, event_id, start_time, additional_table, last_update_time, last_update_by, approved, approved_by, status, primary_gm) VALUES ('$attendee_id', '$event_id', '$start_time', 'true', now(), '$attendee_id', 'true', '$attendee_id', 'APPROVED', 'true') ")) {
			echo "Failed updating GM $attendee_id at $start_times.<br>";
			return false;
			}
		}
	return $event_id;
} 

function update_event($event_id, $event_values)
{
// This function attempts to update an existing event in the database.
extract ($event_values);

if (!($conn = db_connect()))
return false;

	$query = "UPDATE event SET event_title = '$event_title', description = '$description', min_players = '$min_players', max_players = '$max_players', difficulty = '$difficulty', familiarity = '$familiarity', game_system = '$game_system', cost = '$cost', equipment = '$equipment', notes = '$notes', modified = '$timestamp', maturity = '$maturity', event_type = '$event_type', approved = '$approved', show_change = '$show_change', featured = '$featured', cancelled = '$cancelled', change_description = '$change_description', display_org = '$display_org' WHERE event_id = '$event_id'";
//	echo "$query";
if (!pg_query("$query"))
	return false;

}

function print_event_time_start($event_id)
{
if (!($conn = db_connect()))
return false;
$result = pg_query("SELECT event_time.start_time, (event_time.start_time + event.duration) AS end_time FROM event_time, event WHERE event.event_id = event_time.event_id AND event_time.event_id = '$event_id' ORDER BY event_time.start_time");
if (!$result)
return false;
$numrows = pg_num_rows($result); 
for ($i=0; $i < $numrows; $i++) {
$start_time = pg_fetch_result($result,$i,"start_time");
$start_time = strtotime($start_time);
$start_time = date('g:ia D n/j/y', $start_time);
$time_list .= "$start_time \n";
}
return $time_list;
}

function print_event_codes($event_id)
{
if (!($conn = db_connect()))
return false;
$result = pg_query("SELECT start_time FROM event_time WHERE
event_id = '$event_id' ORDER BY start_time");
if (!$result)
return false;
$num = pg_numrows($result);
$i=0;
while ($i < $num) {
$ts = pg_fetch_result($result,$i++,"start_time");
$ts = strtotime($ts);
$ts = strtoupper(date(DH,$ts));
$eventcodes = $eventcodes."$ts"."-"."$event_id\n";
}
return $eventcodes;
}

function print_time_start($start_time)
{
$start_time = strtotime($start_time);
$sttime = date('l ga', $start_time);
return $sttime;
}


function mail_event_confirmation($bodytext, $event_id)
{

//First we lookup the event we are mailing info out about and process it.
$result = recordproc(get_event_details($event_id));
extract ($result);

// Lookup the owner of the event's e-mail attendee_id should be set from our event lookup.
if (!($conn = db_connect()))
return false;
$result = pg_query("SELECT * FROM attendee WHERE
						attendee_id = '$attendee_id'");
if (!$result)
return false;
if (pg_num_rows($result)>0) {
$email_addr = pg_fetch_result($result,0,"email_addr");
}

	//Create list of times the event is supposed to run in.
$start_times = print_event_time_start($event_id);

	//set the heading text for the email based on whether it was initialsubmission, or approved.
	if ($bodytext == 'initialsubmit') {
	  $headingtext = "Thank you $name you have submitted the following event. Please review the following information to verify that it is correct. Also take time to review our GM Policies at http://loki.local/~plummer/uny-con/index.php?uny=gm.php";
	  $subject = "Thank you for submiting an event to UNY-Con III";
	}
	if ($bodytext == approved) {
	  $headingtext = "$first_name your event has been approved or revised by convention staff. The approved version is shown below.";
	  $subject = "UNY-Con Event #$event_id Update";
	}

$headers = "From: UNY-Con Event registration <registration@uny-con.com>";
$message = "$headingtext

Event ID:			$event_id
Event Title:		$event_title
Game System:		$game_system
Min players:		$min_players
Max players:		$max_players
Dificulty:		$difficulty
Knowledge Level:	$familiarity
Maturity:			$maturity
Type of Event:	$event_type
Cost:			$cost
players bring:	$equipment
Description:		$description
Notes:			$notes
You have agreed to run the above event in the following timeslots:
Duration of event: $duration hours.
$start_times";

//	echo "\nSubject: ".nl2br($subject)."<br><br>Headers: ".nl2br($headers)."<br><br>Body:<br>".nl2br($message)."<br><br>";
$email="$email_addr";
// send email to the GM.
if (mail($email, $subject, $message, $headers)) {
// send email to the event coordinators.
	  $headers = "From: $name <$email_addr>";
	  $email = 'events@uny-con.com, tigger00@rochester.rr.com';
	  mail($email, $subject, $message, $headers);
return true;
}
else
return false;
}

function recordproc($result, $i ="0")
{
//Process a given event record (it must still be in the postgres format) to make some handy variables and transform simple numbers to descriptive things.
	$values = pg_fetch_array($result, $i, PGSQL_ASSOC) ;
if (isset($values['first_name']) && isset($values['last_name'])) {
	  $values['name'] = $values['first_name'] . ' ' . $values['last_name'];
}
if ($values['display_org'] == 't' && !empty($values['organization'])) {$values['name'] = $values['organization']; }
if (isset($values['familiarity'])) {
$values['processed_familiarity'] = str_replace("1" , "None", $values['familiarity']);
	  $values['processed_familiarity'] = str_replace("2" , "Basic", $values['processed_familiarity']);
	  $values['processed_familiarity'] = str_replace("3" , "Average", $values['processed_familiarity']);
	  $values['processed_familiarity'] = str_replace("4" , "Expert", $values['processed_familiarity']);
	}
	if (isset($values['difficulty'])) {
	$values['processed_difficulty'] = str_replace("1" , "Easy", $values['difficulty']);
	$values['processed_difficulty'] = str_replace("2" , "Almost Easy", $values['processed_difficulty']);
	$values['processed_difficulty'] = str_replace("3" , "Moderate", $values['processed_difficulty']);
	$values['processed_difficulty'] = str_replace("4" , "Difficult", $values['processed_difficulty']);
	$values['processed_difficulty'] = str_replace("5" , "Impossible", $values['processed_difficulty']);
}
	if (isset($values['maturity'])) {
	$values['processed_maturity'] = str_replace("Y" , "Yes", $values['maturity']);
	$values['processed_maturity'] = str_replace("N" , "No", $values['processed_maturity']);
	$values['processed_maturity'] = str_replace("M" , "Possibly", $values['processed_maturity']);
}
return $values;
}

function get_event_list($searchtype = "all", $search_key = "", $search_string = "", $sortkey = "event.event_type, event.game_system", $sortdir ="ASC")
{
// This function is designed to query the database for events of a given type within a given timeslot
$approved = "AND event.approved = 't'";
if ($_SESSION['admin'] == 't') $approved = '';
if ($sortkey == event_type) $sortkey = $sortkey.' '.$sortdir.', event.game_system';
// connect to db
$conn = db_connect();
if (!$conn)
return false;
	$select = 'SELECT attendee.first_name, attendee.last_name, attendee.organization, event_time.start_time, event_time.assigned_room, event.*  FROM event_time, event, attendee';
if ($searchtype == 'all') 
$result = pg_query("$select WHERE event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id $approved ORDER BY event_time.start_time ASC, $sortkey $sortdir");
if ($searchtype == 'event_type') 
$result = pg_query("$select WHERE event.event_type = '$search_string' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id $approved ORDER BY event_time.start_time ASC, $sortkey $sortdir");
if ($searchtype == 'search') 
$result = pg_query("$select WHERE $search_key ~~* '$search_string' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id $approved ORDER BY event_time.start_time ASC, $sortkey $sortdir");
if ($searchtype == 'gm') 
$result = pg_query("$select WHERE event.attendee_id = '$search_string' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id $approved ORDER BY event_time.start_time ASC, $sortkey $sortdir");
if ($searchtype == 'featured') {
	$select = 'SELECT attendee.first_name, attendee.last_name, attendee.organization, event.*  FROM event, attendee';
	$result = pg_query("$select WHERE event.featured = 't' AND event.attendee_id = attendee.attendee_id AND approved = 't' ORDER BY $sortkey $sortdir");
	}

if (!$result) {
echo 'No data was found';
return false; }  
return $result;

}

function get_gm_events($attendee_id) {
// This function will get all the events a person is running at the con
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT attendee.first_name, attendee.last_name, attendee.organization, event_time.start_time, event_time.assigned_room, event.* FROM event, attendee, event_time WHERE event.attendee_id = '$attendee_id' AND event.attendee_id = attendee.attendee_id AND event.event_id = event_time.event_id ORDER BY event_time.start_time ASC, event.event_type ASC");
if (pg_num_rows($result) == 0)
return false;
return $result;

}

function get_cogm_events($attendee_id, $status) {
// This function will get all the events a person is signed up to co-gm at the convention
// connect to db
$conn = db_connect();
if (!$conn)
return false;
if ($status == approved) $approved = "AND gm.approved = 't' AND gm.denied = 'f'";
if ($status == pending) $approved = "AND gm.approved = 'f' AND gm.denied = 'f'";
if ($status == denied) $approved = "AND gm.denied = 't'";
if ($status == all) $approved = ' ';
$result = pg_query("SELECT attendee.first_name, attendee.last_name, attendee.organization, event_time.start_time, event_time.assigned_room, event.*, gm.approved FROM event, attendee, event_time, gm WHERE gm.gm_id = '$attendee_id' AND gm.event_id = event.event_id AND event.attendee_id = attendee.attendee_id AND event.event_id = event_time.event_id AND gm.start_time = event_time.start_time AND gm.primary_gm = 'f' $approved ORDER BY event_time.start_time ASC, event.event_type ASC");
if (pg_num_rows($result) == 0)
return false;
return $result;
}

function get_event($searchtype = "eventid", $searchterm = "", $sortkey = "event.event_type")
{
// This function is designed to query the database for events of a given type within a given timeslot
// connect to db
$conn = db_connect();
if (!$conn)
return false;
if ($searchtype == 'eventid') 
$result = pg_query("SELECT DISTINCT ON (event.event_id) attendee.first_name, attendee.last_name, attendee.organization, event.*  FROM event, attendee WHERE event.event_id = '$searchterm' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id ORDER BY event.event_id");
if ($searchtype == 'gm') 
$result = pg_query("SELECT DISTINCT ON (event.event_id) attendee.first_name, attendee.last_name, attendee.organization, event.* , event_time.start_time, event_time.assigned_room FROM event, attendee, event_time WHERE event.attendee_id = '$searchterm' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id ORDER BY event.event_id");
if ($searchtype == 'timeslot') 
$result = pg_query("SELECT attendee.first_name, attendee.last_name, attendee.organization, event_time.start_time, event_time.assigned_room, event.*  FROM event_time, event, attendee WHERE event_time.start_time = '$searchterm' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id ORDER BY $sortkey");
if ($searchtype == 'featured') 
$result = pg_query("SELECT attendee.first_name, attendee.last_name, attendee.organization, event.*  FROM event, attendee WHERE event.featured = 't' AND event.attendee_id = attendee.attendee_id ORDER BY $sortkey");

if (!$result) {
echo 'No data was found';
return false; }  
return $result;

}

function add_gm($attendee_id, $event_id, $timeslot)
{
	$conn = db_connect();
	if (!$conn)
		return false;
	$owned_events = pg_fetch_all(get_user_eventids($attendee_id));
	if (is_array($owned_events) && !empty($owned_events)) {
		foreach ($owned_events as $event) {
			if (in_array($event_id,$event)) {
				echo 'yes it works this way';
				$approved = 'true';
				$status = 'APPROVED';
				$primary_gm = 'true';
				break;
				} else {
				$approved = 'false';
				$status = 'PENDING';
				$primary_gm = 'false';
				}
			}
		} else {
		$approved = 'false';
		$status = 'PENDING';
		$primary_gm = 'false';
		}
	$query = "INSERT INTO gm (gm_id, event_id, start_time, additional_table, last_update_time, last_update_by, approved, approved_by, status, primary_gm) VALUES ('$attendee_id', '$event_id', '$timeslot', 'true', now(), '$attendee_id', '$approved', '$attendee_id', '$status', '$primary_gm')";
	$result = pg_query("$query");
	return $result;
}

function add_co_gm($attendee_id, $event_id, $timeslot)
{
	$conn = db_connect();
	if (!$conn)
		return false;
	$result = pg_query("INSERT INTO gm (gm_id, event_id, start_time, primary_gm) VALUES ('$attendee_id', '$event_id', '$timeslot', 'f')");
	return $result;
}

function deny_gm($attendee_id, $event_id, $timeslot)
{
	//Deletes an enty from the cogm database
	$conn = db_connect();
	if (!$conn)
		return false;
	$current_id = $_SESSION['current_attendee_id'];
	$result = pg_query("UPDATE gm SET denied = 't', approved = 'f', status = 'DENIED', last_update_by = '$current_id', approved_by = '$current_id', last_update_time = now() WHERE gm_id = '$attendee_id' AND event_id = '$event_id' AND start_time = '$timeslot'");
	return $result;
}

function delete_gm($attendee_id, $event_id, $timeslot)
{
	//Deletes an enty from the gm table.
	$conn = db_connect();
	if (!$conn)
		return false;
	$result = pg_query("DELETE FROM gm WHERE gm_id = '$attendee_id' AND event_id = '$event_id' AND start_time = '$timeslot'");
	return $result;
}

function get_event_gms ($event_id, $timeslot, $status = "all") {
	//This function gets a list of GMs for a given event in a given timeslot.
	if (!($conn = db_connect()))
		return false;
	if ($status == all) $approved = ' ';
	if ($status == approved) $approved = "AND gm.approved = 't' AND gm.denied = 'f'";
	if ($status == unapproved) $approved = "AND (gm.approved = 'f' OR gm.denied = 't')";	
	$query = "SELECT attendee.first_name, attendee.last_name, attendee.organization, attendee.email_addr, attendee.attendee_id as gm_id, event.*, gm.* FROM event, gm, attendee WHERE event.event_id = '$event_id' AND event.event_id = gm.event_id AND attendee.attendee_id = gm.gm_id AND gm.start_time = '$timeslot' AND gm.primary_gm = 't' $approved ORDER BY attendee.last_name ASC";
//	echo $query;
	$result = pg_query("$query");
	if (!$result) {
		echo 'No one is currently gming this event';
		return false; }  
	return $result;
}

function get_num_of_gms ($event_id, $timeslot, $status = "all") {
	//This function returns the number of gms running an event in a given TS.
	if (!($conn = db_connect()))
		return false;
	if ($status == all) $approved = ' ';
	if ($status == approved) $approved = "AND gm.approved = 't' AND gm.denied = 'f'";
	if ($status == unapproved) $approved = "AND (gm.approved = 'f' OR gm.denied = 't')";	
	$query = "SELECT gm_id FROM gm WHERE event_id = '$event_id' AND start_time = '$timeslot' $approved";
//	echo $query;
	$result = pg_query("$query");
	if (pg_num_rows($result)) $num_of_gms = pg_num_rows($result);
		else $num_of_gms = 0;
	return $num_of_gms;
}

function get_event_cogms($attendee_id, $status ="all")
{
//Gets the cogm's names, ID's, and event info for the events an attendee is the primary gm for.
	$conn = db_connect();
	if (!$conn)
		return false;
	if ($status == all) $approved = ' ';
	if ($status == approved) $approved = "AND gm.approved = 't' AND gm.denied = 'f'";
	if ($status == unapproved) $approved = "AND (gm.approved = 'f' OR gm.denied = 't')";	
	if ($status == pending) $approved = "AND gm.approved = 'f' AND gm.denied = 'f'";
	if ($status == denied) $approved = "AND gm.denied = 't'";
	$result = pg_query("SELECT attendee.first_name, attendee.last_name, attendee.email_addr, event.*, gm.* FROM event, gm, attendee WHERE event.attendee_id = '$attendee_id' AND event.event_id = gm.event_id AND attendee.attendee_id = gm.gm_id AND gm.primary_gm = 'f' $approved ORDER BY gm.start_time ASC, event.event_type ASC, event.event_title ASC, attendee.last_name ASC");
	return $result;
}

function approve_co_gm($attendee_id, $event_id, $timeslot)
{
//approves cogms for an event
	$conn = db_connect();
	if (!$conn)
		return false;
	$current_id = $_SESSION['current_attendee_id'];
	$result = pg_query("UPDATE gm SET approved = 't', denied = 'f', status = 'APPROVED', last_update_by = '$current_id', approved_by = '$current_id', last_update_time = now() WHERE gm_id = '$attendee_id' AND event_id = '$event_id' AND start_time = '$timeslot'");
	return $result;
}

function get_attend_events($attendee_id, $status = "all") {
	// This function will get all the events a person is attending at the con
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	if ($status == 'all')
		$statustype = '';
	if ($status == 'pending')
		$statustype = "AND event_reg.reg_status = 'pending'";
	if ($status == 'approved')
		$statustype = "AND event_reg.reg_status = 'approved'";  
	$result = pg_query("SELECT attendee.first_name, attendee.last_name, event.*, event_reg.start_time, event_reg.reg_status, event_time.assigned_room  FROM event, event_reg, attendee, event_time WHERE event_reg.attendee_id = '$attendee_id' $statustype AND event.event_id = event_reg.event_id AND event.attendee_id = attendee.attendee_id  AND event_time.event_id = event_reg.event_id AND event_time.start_time = event_reg.start_time ORDER BY event_reg.start_time ASC");
	if (pg_num_rows($result) == 0)
		return false;
	return $result;
}

function get_con_attendance_status($attendee_id) {
// This function will get the con status
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT reg_status FROM con_reg WHERE attendee_id = '$attendee_id'");
if (pg_num_rows($result) == 0)
return false;
$status = pg_fetch_result($result,0,"reg_status");
return $status;
}

function get_con_reg_info($attendee_id) {
// This function will get all the info in con_reg for the given attendee_id
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT *, EXTRACT(EPOCH FROM entered) as enteredepoch, EXTRACT(EPOCH FROM modified) as modifiedepoch, EXTRACT(EPOCH FROM checked_in) as checked_inepoch FROM con_reg WHERE attendee_id = '$attendee_id'");
if (pg_num_rows($result) == 0) {
return false;
}
$values = pg_fetch_array($result, 0, PGSQL_ASSOC);
return $values;
}

function get_event_status($attendee_id, $event_id, $time) {
// This function will get the reg status of a given user for a given event.
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT reg_status FROM event_reg WHERE start_time = '$time' AND event_id = '$event_id' AND attendee_id = '$attendee_id'");
if (pg_num_rows($result) == 0)
return false;
$status = pg_fetch_result($result,0,"reg_status");
return $status;
}

function get_con_attendance_day($attendee_id) {
// This function will get the convention attendance day
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT event_day FROM con_reg WHERE attendee_id = '$attendee_id'");
if (pg_num_rows($result) == 0)
return false;
$event_day = pg_fetch_result($result,0,"event_day");
return $event_day;
}

function get_min_ts_reg($event_day) {
	//This function gets the minimum time slot someone can register for based on what day they are registered for.
	// Timeslots for dates
	// 1 - 2 - 3 Friday
	// 4 - 5 - 6 - 7 - 8 Saturday
	// 9 - 10 - 11 Sunday
	// All Week-end is really all

	if ($event_day == 'friday') {
		$min = 1;
		} elseif ($event_day == 'saturday') {
		$min = 3;
		} elseif ($event_day == 'sunday') {
		$min = 8;
		} elseif ($event_day == 'all week-end' || $event_day == 'all-access') {
		$min = 1;
		}
	return $min;
}

function get_max_ts_reg($event_day) {
	//This function gets the max time slot someone can register for based on what day they are registered for.
	// Timeslots for dates
	// 1 - 2 - 3 Friday
	// 4 - 5 - 6 - 7 - 8 Saturday
	// 9 - 10 - 11 Sunday
	// All Week-end is really all

	if ($event_day == 'friday') {
		$max = 3;
		} elseif ($event_day == 'saturday') {
		$max = 7;
		} elseif ($event_day == 'sunday') {
		$max =11;
		} elseif ($event_day == 'all week-end' || $event_day == 'all-access') {
		$max = 11;
		}
	return $max;
}

function get_con_attendance_type($attendee_id) {
// This function will get the convention attendance type
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT reg_type FROM con_reg WHERE attendee_id = '$attendee_id'");
if (pg_num_rows($result) == 0)
return false;
$reg_type = pg_fetch_result($result,0,"reg_type");
return $reg_type;
}

function update_con_status($date_select, $con_status, $attendee_id, $reg_type, $cost, $modified_by_id) {
// This function will update a user's the convention status
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$query = "UPDATE con_reg SET reg_status = '$con_status', event_day = '$date_select', reg_type = '$reg_type', modified = 'now()', cost = '$cost', last_modified_by = '$modified_by_id' WHERE attendee_id = '$attendee_id'";
if (!pg_query("$query")) 
return false;

return true;
}

function check_in_to_con($attendee_id, $modified_by_id) {
// This function will update a user's the convention status
// connect to db
$conn = db_connect();
if (!$conn)
return false;

if (!pg_query("UPDATE con_reg SET checked_in = 'now()', last_modified_by = '$modified_by_id' WHERE attendee_id = '$attendee_id' ")) 
return false;

return true;
}

function insert_con_registration($attendee_id, $event_day, $reg_type, $cost, $reg_status, $modified_by_id) {
// This function will update a user's the convention status
// connect to db
$conn = db_connect();
if (!$conn)
return false;
	if ($reg_type == 'general admit on-site') {
		$check_in = ", checked_in ";
		$check_in_time = ", 'now()' ";
		}
$query = "INSERT INTO con_reg (attendee_id, reg_type, event_day, cost, reg_status, entered, last_modified_by $check_in) VALUES ('$attendee_id', '$reg_type', '$event_day', '$cost', '$reg_status', 'now()', $modified_by_id $check_in_time)";
//	echo "$query<br />";
if (!pg_query("$query"));
return false;

return true;
}

function insert_trans_log($entered_by, $for_attendee_id, $amount, $type) {
// This function will insert an entry into the transaction log.
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$query = "INSERT INTO trans_log (entered_by, for_attendee_id, time, amount, type) VALUES ('$entered_by', '$for_attendee_id', 'now()', '$amount', '$type')";
if (!pg_query("$query"));
return false;

return true;
}

function get_attendee_amount_paid($attendee_id) {
	// This function returns the amount someone has actually paid us. using the attendee databases record of what they paid.
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	//$result = pg_query("SELECT amount_paid FROM attendee WHERE attendee_id = '$attendee_id'");
	$result = pg_query("SELECT total_paid FROM remaining_balance WHERE attendee_id = '$attendee_id'");
	if (pg_num_rows($result) == 0)
		return false;
	$amount_paid = floatval(pg_fetch_result($result,0,"total_paid"));
	return $amount_paid;
}

function update_attendee_amount_paid($attendee_id, $trans_amount) {
	// This function will update how much someone paid us, using the attendee databases record of what they paid.
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	$current_amount_paid = get_attendee_amount_paid($attendee_id);
	$current_amount_paid += $trans_amount;
	if (!pg_query("UPDATE attendee SET amount_paid = '$current_amount_paid' WHERE attendee_id = '$attendee_id' ")) 
		return false;
	return true;
}

function get_attendee_amount_owed($attendee_id) {
	// This function calculates how much an attendee owes us. adding the costs of their events and convention registrations.
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	//first we will get how much they paid for their convention reg.
	//$con_amount_paid = get_con_amount_paid($attendee_id);
	 
	 //Now we get a list of all events they are participating in and iterate through that to total the cost of those events.
	//$LARPevent_id1 = "9153";
	//$LARPevent_id2 = "9154";
	//$number_of_LARPS1 = 0;
	//$number_of_LARPS2 = 0;
	//$result = get_attend_events($attendee_id, all);
	//$event_array = db_result_to_array($result);
	//foreach ($event_array as $row) {
	//	$rowamountpaid = get_event_amount_paid($row['event_id'], $row['starting_timeslot'], $attendee_id);
	//	if (($number_of_LARPS1 == '0' || $row['event_id'] != $LARPevent_id1) && ($number_of_LARPS2 == '0' || $row['event_id'] != $LARPevent_id2)) {
	//		$event_amount_paid += "$rowamountpaid";
	//		}
	//	if ($row['event_id'] == $LARPevent_id1)
	//		$number_of_LARPS1 = $number_of_LARPS1 + 1;
	//	if ($row['event_id'] == $LARPevent_id2)
	//		$number_of_LARPS2 = $number_of_LARPS2 + 1;
	//	unset($rowamountpaid);
	//	}
	//$amount_owed = $con_amount_paid + $event_amount_paid;
	$amount_owed = pg_query("SELECT total_cost FROM remaining_balance WHERE attendee_id = '$attendee_id'");
	if (pg_num_rows($amount_owed) == 0)
		return false;
	$amount_owed2 = floatval(pg_fetch_result($amount_owed,0,"total_cost"));
	return $amount_owed2;
}

function delete_event_reg($event_id, $timeslot, $attendee_id) {
	// This function will delete an event
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	//we best check to make sure they are actually registered before driopping event.
	if (!get_event_status($attendee_id, $event_id, $timeslot)) {
		echo "<p>You do not appear to be registered for the event you are trying to drop</p>\n";
		return false;
		}
	//if the event was approved and had a cost we need to credit their account first.
//	$event_status = get_event_status($attendee_id, $event_id, $timeslot);
//	if ($event_status == 'approved') {
//		$amount_paid = get_event_amount_paid($event_id, $timeslot, $attendee_id);
//		$amount_paid = "-$amount_paid";
//		update_attendee_amount_owed($attendee_id, $amount_paid);
//		}
	if (!pg_query("DELETE FROM event_reg WHERE (start_time = '$timeslot' AND event_id = '$event_id' AND attendee_id = '$attendee_id')"))
		return false;
	return true;
}


function get_max_players_for_event($event_id) {
// This function will get the con status
// connect to db
$conn = db_connect();
if (!$conn)
return false;

$result = pg_query("SELECT max_players FROM event WHERE event_id = '$event_id'");

if (pg_num_rows($result) == 0)
return false;
$max_players = pg_fetch_result($result,0,"max_players");
return $max_players;
}

function get_current_num_players($event_id, $start_time) {
// This function will get the cirrent number of players in a game
// connect to db
$conn = db_connect();
if (!$conn)
return false;

$result = pg_query("SELECT attendee_id FROM event_reg WHERE event_id = '$event_id' AND start_time = '$start_time'");
$current_players = pg_num_rows($result);

return $current_players;
}

function add_event_reg($event_id, $start_time, $attendee_id) {
	// This function inserts a registration into the database. and return the status of that registartion.
	// connect to db
	$entered_by = $_SESSION['attendee_id'];
	$conn = db_connect();
	if (!$conn)
		return false;
	$event_cost = get_event_cost($event_id);
	$reg_status = 'pending';
	if ($event_cost == '0.00' || $_SESSION['admin'] == 't') $reg_status = 'approved';
	if ($event_cost > '0.00') {
		$amount_owed = get_attendee_amount_owed($attendee_id);
		$amount_paid = get_attendee_amount_paid($attendee_id);
		$balance = $amount_owed - $amount_paid;
		$balance += $event_cost;
		if ($balance <= '0') $reg_status = 'approved';
		}
	$query = "INSERT INTO event_reg (event_id, start_time, attendee_id, entered, reg_status, cost, entered_by) VALUES ('$event_id', '$start_time', '$attendee_id', 'now()', '$reg_status', '$event_cost', '$entered_by')" ;
	$max_players = get_max_players_for_event($event_id);
	$curr_players = get_current_num_players($event_id, $start_time);
	if ($currplayers >= $max_players) {
		$reg_status = 'full';
		}
	if ($curr_players < $max_players) {
		if (!pg_query("$query")) return false;
		}
	return $reg_status;
}

function get_event_list_for_signup($time, $searchtype = "", $searchterm = "", $sortkey = "event.event_type, event.game_system", $sortdir ="ASC") {
	// This function is designed to query the database for events of a given type within a given timeslot
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	  if ($sortkey == event_type) $sortkey = $sortkey.' '.$sortdir.', event.game_system';
	$approved = "AND event.approved = 't'";
	if (!empty($searchtype) && !empty($searchterm)) $searchval = "AND $searchtype = '$searchterm'";
	$query = "SELECT attendee.first_name, attendee.last_name, event_time.start_time, event_time.assigned_room, event.*  FROM event_time, event, attendee WHERE event_time.start_time = '$time' AND event.event_id = event_time.event_id AND event.attendee_id = attendee.attendee_id AND event.cancelled != 't' $searchval $approved ORDER BY $sortkey $sortdir";
	$result = pg_query("$query");
	if (pg_num_rows($result) == '0') {
		echo 'No data was found';
		return false;
		}
	return $result;
}

function get_event_cost($event_id) {
// This function will get the con status
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT cost FROM event WHERE event_id = '$event_id'");
if (pg_num_rows($result) == 0)
return false;
$cost = floatval(pg_fetch_result($result,0,"cost"));
return $cost;
}

function get_event_amount_paid($event_id, $time, $attendee_id) {
// This function returns the amount someone paid for an event.
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT cost FROM event_reg WHERE event_id = '$event_id' AND attendee_id = '$attendee_id' AND start_time = '$time'");
if (pg_num_rows($result) == 0)
return false;
$amount_paid = floatval(pg_fetch_result($result,0,"cost"));
return $amount_paid;
}

function get_con_amount_paid($attendee_id) {
// This function returns the amount someone paid for their convention registration.
// connect to db
$conn = db_connect();
if (!$conn)
return false;
$result = pg_query("SELECT cost FROM con_reg WHERE attendee_id = '$attendee_id'");
if (pg_num_rows($result) == 0)
return false;
$amount_paid = floatval(pg_fetch_result($result,0,"cost"));
return $amount_paid;
}

function update_event_reg_status($event_id, $start_time, $attendee_id, $registration_status) {
// This function will update the status of an event to the specified status.
// connect to db
$conn = db_connect();
if (!$conn)
return false;

if (!pg_query("UPDATE event_reg SET reg_status = '$registration_status', modified = 'now()' WHERE event_id='$event_id' AND start_time='$start_time' AND attendee_id='$attendee_id'"))
return false;

return true;
}

function check_attendee_event($attendee_id, $event_id, $start_time) {
	//This function checks if an attendee is running or playing a given event in a given time and returns which they are doing.
$conn = db_connect();
if (!$conn)
return false;
$query ="SELECT event_id FROM event_reg WHERE attendee_id = '$attendee_id' AND start_time = '$start_time' AND event_id = '$event_id'";
$result = pg_query("$query");
if (pg_num_rows($result) > 0) {return 'player'; }
unset($result, $query);
$query = "SELECT event_id FROM gm WHERE gm_id = '$attendee_id' AND start_time = '$start_time' AND event_id = '$event_id'";
$result = pg_query("$query");
if (pg_num_rows($result) > 0) { return 'gm'; }
unset($result, $query);
return false;
}

function check_attendee_timeslot_reg($attendee_id, $start_time_pass, $duration) {
	//This function checks whether a attendee is registered or running an event in the given timeslot.
$conn = db_connect();
if (!$conn)
return false;

//echo '<BR>Running the check_attendee_timeslot_reg.<BR>';

$result = pg_query("SELECT event_reg.event_id as event_id, event_reg.start_time as start_time, event_reg.start_time + event.duration as end_time FROM event_reg, event WHERE event.event_id = event_reg.event_id AND event_reg.attendee_id = '$attendee_id'");
$event_reg_array = pg_fetch_all($result);
if (is_array($event_reg_array) && !empty($event_reg_array)) {
		foreach ($event_reg_array as $event_reg) {
			$time1 = strtotime($start_time_pass);
			$time_end1 = $time1 + ($duration * 3600);
			$time_end_stamp = date("Y-m-d H:i:s-05", $time_end1);
			$timestamp1 = date("Y-m-d H:i:s-05", $time1);
			$event_start_time = $event_reg['start_time'];
			//echo "Checking against event starting at $event_start_time<BR>";
			$event_end_time = $event_reg['end_time'];
			//echo "Checking against event ending at $event_end_time<BR>";
			if(!($timestamp1 == $event_end_time) && !($time_end_stamp == $event_start_time)) {
				//echo "Registering for event at $timestamp1<BR>";
				//echo "For $duration<BR>";

	  			for ($i=0; $i <= $duration; $i++) {
					$time = strtotime($start_time_pass);
					$time = $time + ($i * 3600);
					$timestamp = date("Y-m-d H:i:s-05", $time);
					$event_reg_start_time = $event_reg['start_time'];
					$event_reg_end_time = $event_reg['end_time'];
					//echo "Interval $i Time $timestamp Start Time $event_reg_start_time End Time $event_reg_end_time<BR>";
					if (($timestamp >= $event_reg_start_time) && ($timestamp <= $event_reg_end_time))
						return true;
				}
			}
		}
}
unset($result);

$result = pg_query("SELECT event.event_id as event_id, event_time.start_time as start_time, event_time.start_time + event.duration as end_time FROM event_time, event WHERE event.attendee_id = '$attendee_id' AND event_time.event_id = event.event_id");
$event_organizer_array = pg_fetch_all($result);
if (is_array($event_organizer_array) && !empty($event_organizer_array)) {
		foreach ($event_organizer_array as $event_organizer) {
			$time1 = strtotime($start_time_pass);
			$time_end1 = $time1 + ($duration * 3600);
			$time_end_stamp = date("Y-m-d H:i:s-05", $time_end1);
			$timestamp1 = date("Y-m-d H:i:s-05", $time1);
			$event_start_time = $event_organizer['start_time'];
			//echo "Checking against event starting at $event_start_time<BR>";
			$event_end_time = $event_organizer['end_time'];
			//echo "Checking against event ending at $event_end_time<BR>";
			if(!($timestamp1 == $event_end_time) && !($time_end_stamp == $event_start_time)) {
				//echo "Registering for event at $timestamp1<BR>";
				//echo "For $duration<BR>";

	  			for ($i=0; $i <= $duration; $i++) {
					$time = strtotime($start_time_pass);
					$time = $time + ($i * 3600);
					$timestamp = date("Y-m-d H:i:s-05", $time);
					$event_organizer_start_time = $event_organizer['start_time'];
					$event_organizer_end_time = $event_organizer['end_time'];
					//echo "Interval $i Time $timestamp Start Time $event_organizer_start_time End Time $event_organizer_end_time<BR>";
					if (($timestamp >= $event_organizer_start_time) && ($timestamp <= $event_organizer_end_time))
						return true;
				}
			}
		}
}
unset($result);

$result = pg_query("SELECT event.event_id as event_id, gm.start_time as start_time, gm.start_time + event.duration as end_time FROM gm, event WHERE gm.event_id = event.event_id AND gm.gm_id = '$attendee_id'");
$event_gm_array = pg_fetch_all($result);
if (is_array($event_gm_array) && !empty($event_gm_array)) {
		foreach ($event_gm_array as $event_gm) {
			$time1 = strtotime($start_time_pass);
			$time_end1 = $time1 + ($duration * 3600);
			$time_end_stamp = date("Y-m-d H:i:s-05", $time_end1);
			$timestamp1 = date("Y-m-d H:i:s-05", $time1);
			$event_start_time = $event_gm['start_time'];
			//echo "Checking against event starting at $event_start_time<BR>";
			$event_end_time = $event_gm['end_time'];
			//echo "Checking against event ending at $event_end_time<BR>";
			if(!($timestamp1 == $event_end_time) && !($time_end_stamp == $event_start_time)) {
				//echo "Registering for event at $timestamp1<BR>";
				//echo "For $duration<BR>";

	  			for ($i=0; $i <= $duration; $i++) {
					$time = strtotime($start_time_pass);
					$time = $time + ($i * 3600);
					$timestamp = date("Y-m-d H:i:s-05", $time);
					$event_gm_start_time = $event_gm['start_time'];
					$event_gm_end_time = $event_gm['end_time'];
					//echo "Interval $i Time $timestamp Start Time $event_gm_start_time End Time $event_gm_end_time<BR>";
					if (($timestamp >= $event_gm_start_time) && ($timestamp <= $event_gm_end_time))
						return true;
				}
			}
		}
}
unset($result);

/*
$result = pg_query("SELECT event_id FROM event_reg WHERE attendee_id = '$attendee_id' AND start_time between '$start_time' and '$start_time + $duration'");
if (pg_num_rows($result) > 0)
return true;
unset($result);

$result = pg_query("SELECT event.event_id FROM event_time, event WHERE event.attendee_id = '$attendee_id' AND event_time.event_id = event.event_id AND event_time.start_time between '$start_time' and '$start_time + $duration'");
if (pg_num_rows($result) > 0)
return true;
unset($result);

$result = pg_query("SELECT event_id FROM gm WHERE gm_id = '$attendee_id' AND start_time between '$start_time' and '$start_time + $duration'");
if (pg_num_rows($result) > 0)
return true;

*/

return false;
}

function eventreg_confirmation_email($reg_attendee_id, $event_id, $timeslot) {
//First we lookup the event we are mailing info out about and process it.
$result = recordproc(get_event_details($event_id));
extract ($result);
// Lookup the registering person's e-mail and info
if (!($conn = db_connect()))
return false;
$result = pg_query("SELECT * FROM attendee WHERE
						attendee_id = '$reg_attendee_id'");
if (!$result)
return false;
if (pg_num_rows($result)>0) {
$reg_email_addr = pg_fetch_result($result,0,"email_addr");
$reg_first_name = pg_fetch_result($result,0,"first_name");
$reg_last_name = pg_fetch_result($result,0,"last_name");
$reg_name = "$reg_first_name $reg_last_name";
}
$headers = "From: $reg_name <$reg_email_addr>";
$subject = "$reg_name signed up for TS$timeslot"."$event_id";
$message = "$reg_name signed up for the following event:
Registering user's Attendee ID: $reg_attendee_id

Timeslot:		$timeslot
Registering users Attendee ID: $reg_attendee_id
Event ID:		$event_id
Event Title:		$event_title
Game System:		$game_system
Type of Event:	$event_type
# of timslots:	$num_of_timeslots
Cost:			$cost";

//	echo "The following email would be sent<br>\nSubject: ".nl2br($subject)."<br><br>Headers: ".nl2br($headers)."<br><br>Body:<br>".nl2br($message)."<br><br>";
// send email to the event coordinators.
	  $email = 'registration@uny-con.com, tigger00@rochester.rr.com';
	  mail($email, $subject, $message, $headers);
return true;
}


function eventdel_confirmation_email($reg_attendee_id, $event_id, $timeslot) {
//First we lookup the event we are mailing info out about and process it.
$result = recordproc(get_event_details($event_id));
extract ($result);
// Lookup the registering person's e-mail and info
if (!($conn = db_connect()))
return false;
$result = pg_query("SELECT attendee.last_name, attendee.first_name, attendee.email_addr, event_reg.* FROM attendee, event_reg WHERE attendee.attendee_id = '$reg_attendee_id' AND event_reg.attendee_id = attendee.attendee_id AND event_reg.event_id = '$event_id'");
if (!$result)
return false;
if (pg_num_rows($result)>0) {
$reg_email_addr = pg_fetch_result($result,0,"email_addr");
$reg_first_name = pg_fetch_result($result,0,"first_name");
$reg_last_name = pg_fetch_result($result,0,"last_name");
$reg_status = pg_fetch_result($result,0,"reg_status");
$reg_name = "$reg_first_name $reg_last_name";
}
$headers = "From: $reg_name <$reg_email_addr>";
$subject = "$reg_name dropped event TS$timeslot"."$event_id";
$message = "$reg_name dropped the following event:
Registering user's Attendee ID: $reg_attendee_id

The event status was: $reg_status
Timeslot:		$timeslot
Event ID:		$event_id
Event Title:		$event_title
Game System:		$game_system
Type of Event:	$event_type
# of timslots:	$num_of_timeslots
Cost:			$cost";

//	echo "The following email would be sent<br>\nSubject: ".nl2br($subject)."<br><br>Headers: ".nl2br($headers)."<br><br>Body:<br>".nl2br($message)."<br><br>";
// send email to the event coordinators.
	  $email = 'registration@uny-con.com, tigger00@rochester.rr.com';
	  mail($email, $subject, $message, $headers);
return true;
}

function check_for_rpga($result) {
// This function takes a given postgres result resource and checks it for RPGA in the event type.
	if (pg_numrows($result) == '0') return false;
	$num = pg_numrows($result);
	$i = 0;
	for ($i = 0; $i < $num; $i++) {
		$event_type = pg_fetch_result($result, $i, event_type);
		if ($event_type == 'RPGA') {
			return true;
			break;
			}
		}
	return false;
}

function get_event_attendees ($event_id, $timeslot) {
	//This function gets a list of People's names and email addresses signed up for a given event_id in a given timeslot.
	if (!($conn = db_connect()))
		return false;
	$result = pg_query("SELECT attendee.first_name, attendee.last_name, attendee.attendee_id, attendee.email_addr, event_reg.reg_status FROM attendee, event_reg WHERE event_reg.event_id = '$event_id' AND event_reg.start_time = '$timeslot' AND event_reg.attendee_id = attendee.attendee_id ORDER BY attendee.last_name");
	if (!$result) {
		echo 'No one is currently registered for this event';
		return false; }  
	return $result;
}

function write_to_file($somecontent, $filename) {
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
	// open file in append mode and write entries.
	if (!$fp = fopen($filename, 'ab')) {
		print "Cannot open file ($filename)";
		exit;
		}
		
	// Write $somecontent to our opened file.
	if (!fwrite($fp, $somecontent)) {
		print "Cannot write to file ($filename)";
		exit;
		}
	//print "Success, wrote ($someconent entries) to file ($filename)";
	fclose($fp);
	} # close iswriteable if
}

function get_rooms()
{
// query database for a list of rooms
$conn = db_connect();
$query = 'SELECT room_name FROM rooms ORDER BY room_name ASC'; 
$result = pg_query($query);
if (!$result)
return false;
$num_rooms = pg_num_rows($result);
if ($num_rooms ==0)
return false;  
$result = db_result_to_array($result);
return $result; 
}

function update_event_room($room, $timeslot, $event_id) {
	// This function will get the con status
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return false;
	if (!pg_query("UPDATE event_time SET assigned_room = '$room' WHERE event_id = '$event_id' AND start_time = '$timeslot'")) 
		return false;
	return true;
}

function get_attendees_with_pending($type) {
	//this function returns an array of all attendee_ids with pending convention status.
	if (!db_connect())
		return false;
	if ($type == 'convention')
		$query = "SELECT con_reg.attendee_id FROM attendee, con_reg WHERE attendee.attendee_id = con_reg.attendee_id AND con_reg.reg_status = 'pending' ORDER BY attendee.last_name ASC, attendee.first_name ASC";
	if ($type == 'event')
		$query = "SELECT DISTINCT event_reg.attendee_id, first_name, last_name FROM attendee, con_reg WHERE attendee.attendee_id = event_reg.attendee_id AND event_reg.reg_status = 'pending' ORDER BY attendee.last_name ASC, attendee.first_name ASC";
	$result = pg_query("$query");
	$attendee_id_array = db_result_to_array($result);
	return $attendee_id_array;
}

function get_attendees_who_owe_old() {
	$conn = db_connect();
	if (!$conn)
		return false;
	$query = "SELECT * FROM attendee ORDER BY last_name ASC, first_name ASC";
	$result = pg_query($query);
	$attendee_id_array = db_result_to_array($result);
	$i = 0;
	foreach ($attendee_id_array as $id_row) {
		$attendee_id = $id_row['attendee_id'];
		$amount_owed = get_attendee_amount_owed($attendee_id);
		$amount_paid = get_attendee_amount_paid($attendee_id);
		$balance = $amount_owed - $amount_paid;
		if ($balance > 0) {
			$attendees_who_owe[$i] = $id_row;
			unset($temp_attendee_id);
			$i++;
			}
		unset($attendee_id, $amount_owed, $amount_paid, $balance);
		}
	return $attendees_who_owe;
}

function get_attendees_who_owe() {
	$conn = db_connect();
	if (!$conn)
		return false;
	$query = "SELECT attendee.*, EXTRACT(EPOCH FROM attendee.last_login) as last_loginepoch, EXTRACT(EPOCH FROM attendee.modified) as modifiedepoch, EXTRACT(EPOCH FROM attendee.created) as createdepoch, EXTRACT(EPOCH FROM checked_in) as checked_inepoch, remaining_balance.* FROM remaining_balance, attendee, con_reg WHERE remaining_balance > '0' AND attendee.attendee_id = remaining_balance.attendee_id AND attendee.attendee_id = con_reg.attendee_id ORDER BY attendee.last_name ASC, attendee.first_name ASC";
	$result = pg_query($query);
	$attendee_id_array = db_result_to_array($result);
	return $attendee_id_array;
}

function get_badge_cost($badge_id) {
	$conn = db_connect();
	if (!$conn)
		return false;
	$query = "SELECT cost FROM con_cost WHERE badge_type_id = '$badge_id'";
	$result = pg_query($query);
	if (pg_num_rows($result) == '1') {
		$cost = pg_fetch_result($result, cost);
		return $cost;
		} else {
		$cost = '8000';
		return $cost;
		}
}

function check_attendee_time($attendee_id, $time_slot)
{
	$query_run = "select count(1) from gm where $attendee_id = gm_id and $time_slot = start_time" ;
	$query_play = "select count(1) from event_reg where $attendee_id = attendee_id and $time_slot = start_time";

	if ($query_run > 0) {
		return "RUNNING";
		}
	if ($query_play > 0) {
		return "PLAYING";
		}
	else return "OPEN";

}

function get_number_of_events_run($attendee_id) {
	//returns the number of approved non pending timeslots a given attendee is running.
	if (!db_connect())
		return false;
	$query = "SELECT sum FROM num_of_hours_run WHERE gm_id = '$attendee_id'";
	$result = pg_query($query);
	if (pg_numrows($result) < 1 ) {
		return '0';
		}
	$num_gm_events = pg_fetch_result ($result, 0, sum);
	return $num_gm_events;
}

function insert_coupon($values) {
	//Inserts a new coupon into the coupon table.
	if (!db_connect())
		return false;
	extract($values);
	$attendee_id = $_SESSION['attendee_id'];
	$query = "INSERT INTO coupons (description, amount, coupon_code, active, created_by, created_on) VALUES ('$description', '$amount', '$coupon_code', '$active', '$attendee_id', 'now()')";
	if (pg_query($query))  {
		return true; 
		} else {
		echo 'There was an error inserting the coupon into the database.';
		return false;
		}
}

function generate_coupon_code_unique($prefix)
{
	$strlen = strlen($prefix);
	$length = 6-$strlen; 
	$code = random_alphanum($length);
	$coupon_code = "$prefix$code";
	$result = get_coupon_codes();
	$result = pg_fetch_array($result);
		if(in_array($coupon_code, $result))
		{
			while(in_array($coupon_code, $result['coupon_code']))
			{
			$code = random_alphanum($length);
			$coupon_code = "$prefix$code";
			}
		}
	return($coupon_code);
}

?>